<template>
  <div>
    <div class="top-panel__box">
      <el-form :model="dataForm" ref="dataForm" size="small" label-width="10px">
        <el-row>
          <el-col :span="3">
            <el-form-item prop="freeCondition">
              <el-input placeholder="姓名/手机/工号" v-model="dataForm.freeCondition" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item prop="organizationId">
              <organization-cascader :flag="'id'" v-model="dataForm.organizationId" clearable></organization-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item prop="roleId">
              <el-select placeholder="选择职务" v-model="dataForm.roleId" clearable filterable>
                <el-option v-for="item in roleList" :key="item.roleId" :value="item.roleId" :label="item.roleName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item prop="userStatus">
              <el-select placeholder="状态" v-model="dataForm.userStatus" clearable>
                <el-option v-for="(value, key) in dicts['user_status'].childMap" :key="key" :value="key" :label="value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item prop="latestLoginTime">
              <el-date-picker type="date" v-model="dataForm.latestLoginTime" style="width:200px" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" placeholder="最后登录时间" clearable></el-date-picker>
            </el-form-item>
          </el-col>
<!--          <el-col :span="3">-->
<!--            <el-form-item label-width="25px" prop="labelId">-->
<!--              <el-select placeholder="标签" v-model="dataForm.labelId" clearable filterable>-->
<!--                <el-option v-for="item in labelList" :key="item.labelId" :value="item.labelId" :label="item.labelName">{{ item.labelName }}</el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" @click="queryByConditionList(1)">
                <fa-icon class="fa-search" /> 查询
              </el-button>
              <el-button plain @click="onReset">
                <fa-icon class="fa-refresh" />重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-row>
      <el-row>
        <el-col>
          <el-button type="primary" size="small" @click="dialog.addUserDialog=true">
            <fa-icon class="fa-plus" />新增管理员</el-button>
<!--          <el-button size="small" plain @click="dialog.exportDialog=true">-->
<!--            <fa-icon class="fa-upload" />导入</el-button>-->
<!--          <el-button type="" size="small" plain @click="dialog.labelDialog=true">-->
<!--            <fa-icon class="fa-tag" />管理标签</el-button>-->
<!--          <el-button type="" size="small" plain @click="changeStatus('CLOSE')">-->
<!--            批量停用</el-button>-->
<!--          <el-button type="" size="small" plain @click="changeStatus('BATCHFROZEN')">-->
<!--            批量冻结</el-button>-->
          <!-- <el-button type="" size="small" plain>
            批量重置密码</el-button>
          <el-button type="" size="small" plain>
            批量修改机构</el-button> -->
          <tooltip :tooltipOption="tooltipOption" />
        </el-col>
      </el-row>
    </el-row>
    <el-row class="table-top">
      <el-table :data="dataList" v-loading="tableLoading" tooltip-effect="light" class="tc-table" size="small" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" fixed="left"></el-table-column>
        <template v-for="(column, index) in HEAD_LIST">
          <el-table-column :prop="column.prop" :label="column.label" :key="index" :width="column.width" :show-overflow-tooltip="true" />
        </template>
        <el-table-column prop="operation" class-name="oper-col" label="操作" :width="320">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain @click="setUserData(scope.row)">设置</el-button>
            <el-button v-if="scope.row.userStatus !== 'CLOSE'" size="mini" type="info" plain @click="changeStatus('CLOSE', scope.row)">停用</el-button>
            <el-button v-if="scope.row.userStatus === 'CLOSE'" size="mini" type="success" plain @click="changeStatus('NORMAL', scope.row)">启用</el-button>
            <el-button v-if="scope.row.userStatus !== 'FROZEN'" size="mini" type="warning" plain @click="changeStatus('FROZEN', scope.row)">冻结</el-button>
            <el-button v-if="scope.row.userStatus === 'FROZEN'" size="mini" type="warning" plain @click="changeStatus('NORMAL1', scope.row)">解冻</el-button>
            <!-- <el-button size="mini" type="danger" plain @click="deleteRow(scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="pagination-top">
      <pagination :pageNum.sync="dataForm.pageNum" :curSizes.sync="dataForm.pageSize" :total="total" @getList="queryByConditionList" />
    </el-row>
    <!--标签管理-->
<!--    <el-dialog title="导入" :visible.sync="dialog.exportDialog" width="40%" :close-on-click-modal="false">-->
<!--      <import-file v-if="dialog.exportDialog" @updataData="updataData" />-->
<!--    </el-dialog>-->
    <!--标签管理-->
    <el-dialog title="标签管理" :visible.sync="dialog.labelDialog" width="50%" :close-on-click-modal="false">
      <label-msg v-if="dialog.labelDialog" @uppdateUser="updataData" @close="closeLabelEvent"/>
    </el-dialog>
    <!--管理员设置-->
    <el-dialog title="管理员设置" :visible.sync="dialog.setDialog" width="50%" :close-on-click-modal="false">
      <set-user v-if="dialog.setDialog" :userData="userData" :roleList="roleList" @uppdateUser="updataData" @close="closeSetUser" />
    </el-dialog>
    <!--新增用户-->
    <el-dialog title="新增管理员" :visible.sync="dialog.addUserDialog" width="24%" :close-on-click-modal="false">
      <add-or-edit-user v-if="dialog.addUserDialog" :roleList="roleList" @uppdateUser="updataData" />
    </el-dialog>
    <!--修改用户账号状态-->
    <el-dialog :title="statusMap[statusWillUpdate]+'管理员'" :visible.sync="dialog.changeStatusDialog" width="34%" :close-on-click-modal="false">
      <change-status v-if="dialog.changeStatusDialog" @close="closeStatusDialog" :changeType="changeType" :edit-data="changeStatusData" @uppdateUser="updataData" />
    </el-dialog>
  </div>
</template>

<script>
import { common } from '@/utils/common'
import { CONSTANT_OBJ } from '@/utils/constant'
import { AddOrEditUser, LabelMsg, SetUser, ChangeStatus } from './components'
import OrganizationCascader from '@/components/organizationCascader'
import api from './api'
import { HEAD_LIST } from './js/contant'
import { mapState } from 'vuex'
import ImportFile from './components/ImportFile'
export default {
  components: { LabelMsg, AddOrEditUser, SetUser, OrganizationCascader, ChangeStatus, ImportFile },
  data () {
    return {
      HEAD_LIST,
      // 弹框开关
      tooltipOption: {
        title: '帮助提示',
        options: [
          '1、职务代表操作权限和数据权限，操作权限是指具有该职务的用户是否能查看、新增、编辑、删除某些数据，数据权限是指具有该角色的用户能操作的数据的范围；',
          '2、超级管理员的权限是系统默认的最大权限的角色，不能修改；',
          '3、需要删除职务时必须先清除该职务下的所有成员。'
        ]
      },
      dialog: {
        exportDialog: false,
        labelDialog: false,
        addUserDialog: false,
        setDialog: false,
        changeStatusDialog: false
      },
      statusMap: {
        'FROZEN': '冻结',
        'BATCHFROZEN': '批量冻结',
        'NORMAL': '启用',
        'NORMAL1': '解冻',
        'CLOSE': '停用'
      },
      statusWillUpdate: '',
      multipleSelection: [],
      roleList: [],
      userData: {},
      dataForm: {
        freeCondition: '',
        userStatus: '',
        latestLoginTime: null,
        organizationId: '',
        roleId: '',
        labelId: '',
        pageNum: 1,
        pageSize: 10
      },
      tableLoading: false,
      total: 0,
      dataList: [],
      labelList: [],
      changeStatusData: {},
      changeType: 'NOT'
    }
  },
  mounted () {
    this.queryRoleList()
    this.getLabel()
    this.queryByConditionList()
  },
  methods: {
    // 查询标签
    getLabel (val) {
      this.tableLoading = true
      api.postQueryLabelData({ pageSize: 999 }).then(res => {
        const { responseCode, data } = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          this.labelList = data.list || []
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    closeLabelEvent (val) {
      switch (val) {
        case 'save':
          this.dialog.labelDialog = false
          this.queryByConditionList(1)
          break
        case 'close':
          this.dialog.labelDialog = false
          break
      }
    },
    // 查询职务
    queryRoleList () {
      api.postQueryRoleData({
        pageNum: 1,
        pageSize: 999
      }).then(res => {
        const { responseCode, data } = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          this.roleList = data.list || []
        }
      })
    },
    /**
     * @description 查询列表
     */
    queryByConditionList (val) {
      this.dataForm.pageNum = val || this.dataForm.pageNum
      this.tableLoading = true
      api.postQueryByConditionData(this.dataForm).then(res => {
        const { responseCode, data } = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          data.list.forEach(v => {
            v.newGender = this.dicts['gender'].childMap[v.gender] || v.gender
            v.newUserStatus = this.dicts['user_status'].childMap[v.userStatus] || v.userStatus
            v.newOnlineStatus = this.dicts['online_status'].childMap[v.onlineStatus] || v.onlineStatus
            v.newLabelNames = v.labelList && v.labelList.map(u => u.labelName).join(',')
            v.newRoleName = v.roleList && v.roleList.map(u => u.roleName).join(',')
          })
          this.dataList = data.list || []
          this.total = parseInt(data.total) || 0
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    /**
     * @description 设置管理员
     */
    setUserData (row) {
      this.userData = { ...row }
      this.dialog.setDialog = true
    },
    /**
    * @description 重置
     */
    onReset () {
      // 清空查询条件
      common.resetData(this.dataForm, { pageNum: 1, pageSize: 20 })
    },
    // 导出返回
    updataData (data = 'export') {
      this.dialog[`${data}Dialog`] = false
      this.queryByConditionList(1)
    },
    // 多选
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 修改用户状态弹窗
    changeStatus (userStatus, row) {
      if (userStatus === 'FROZEN') {
        this.changeType = 'FROZEN'
      } else if (userStatus === 'NORMAL1') {
        this.changeType = 'UNFROZEN'
      } else if (userStatus === 'BATCHFROZEN') {
        this.changeType = 'BATCHFROZEN'
      } else {
        this.changeType = 'NOT'
      }
      this.statusWillUpdate = userStatus
      if (userStatus === 'NORMAL1') {
        userStatus = 'NORMAL'
      }
      let userList = []
      let idList = []
      if (row) {
        userList.push(row)
        idList.push(row.userId)
      } else {
        if (!this.multipleSelection || this.multipleSelection.length === 0) {
          this.$message.error('请选择用户')
          return false
        }
        userList = this.multipleSelection
        idList = this.multipleSelection.map(v => v.userId)
      }
      this.changeStatusData = { userList, userStatus, idList }
      this.dialog.changeStatusDialog = true
    },
    // 删除
    deleteRow (row) {
      this.$confirm(`<div style="padding-left: 50px"><strong style="font-size: 16px">删除管理员确认</strong><div>确认是否删除 ${row.realName}（${row.userName}） 管理员？</div></div>`, '确认提示', {
        dangerouslyUseHTMLString: true
      }).then(() => {
        api.deleteUser(row.userId).then(res => {
          this.queryByConditionList(1)
        })
      })
    },
    closeSetUser () {
      this.dialog.setDialog = false
      this.queryRoleList()
      this.getLabel()
      this.queryByConditionList()
    },
    closeStatusDialog () {
      this.dialog.changeStatusDialog = false
    }
  },
  computed: {
    ...mapState({
      dicts: state => state.common.dicts
    })
  }
}
</script>

<style lang="less" scoped>
@import "../../assets/css/global.less";
.table-top {
  margin-top: 20px;
}
.tc-table-box {
  border: 1px solid @main-border-color;
  border-bottom: none;
  width:100%;
}

.tc-table-box .el-table thead{
  color: #707277;
  background-color: @panel-color !important;
}
.tc-table-box th{
  background-color: @panel-color !important;
}
</style>
